/*
 * @Author: 刘美红 liumeihong@llootong.com
 * @Date: 2025-04-17 16:54:33
 * @LastEditors: 刘美红 liumeihong@llootong.com
 * @LastEditTime: 2025-04-25 11:42:24
 * @FilePath: \xgjd-app\src\utils\request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import type { RequestConfig, ResponseData } from './types';
import { useUserStore } from '@/stores/user';

// 定义基础配置
const BASE_URL =
  import.meta.env.VITE_AXIOS_BASEAPI_URL || 'https://api.example.com';
const TIMEOUT = 15000;

// 请求队列（用于处理重复请求）
const requestQueue = new Map();

// 创建请求实例
const service = async <T = any>(
  config: RequestConfig
): Promise<ResponseData<T>> => {
  if (config.showLoading) {
    uni.showToast({ title: '请求中', icon: 'loading', duration: 15000 });
  }
  // 处理完整URL
  const fullUrl = config.url.startsWith('http')
    ? config.url
    : `${BASE_URL}${config.url}`;
  // 生成请求唯一标识
  const requestKey = `${config.method?.toUpperCase()}|${fullUrl}|${JSON.stringify(
    config.data
  )}`;

  // 重复请求检查
  if (requestQueue.has(requestKey)) {
    return requestQueue.get(requestKey);
  }

  // 合并配置
  const mergedConfig: UniApp.RequestOptions = {
    url: fullUrl,
    method: config.method || 'GET',
    timeout: config.timeout || TIMEOUT,
    header: {
      'Content-Type': 'application/json',
      ...config.header,
    },
    data: config.data,
  };

  try {
    // 请求拦截器
    const userStore = useUserStore();
    const res = await userStore.getToken();

    if (
      !res.token &&
      !fullUrl.includes('login') &&
      !fullUrl.includes('getYhxx')
    ) {
      // uni.showToast({ title: "登录已过期，请重新登录", icon: "none" });
      uni.reLaunch({ url: '/pages/login/index' });
    } else {
      mergedConfig.header!['Authorization'] = res.token;
    }
  } catch (e) {
    console.error(e);
  }

  // 加入队列
  const requestPromise = new Promise<ResponseData<T>>((resolve, reject) => {
    uni.request({
      ...mergedConfig,
      success: (res) => {
        // 响应拦截器
        if (res.statusCode === 401) {
          userStore.logout();
          uni.reLaunch({ url: '/pages/login/index' });
          reject(new Error('登录已过期，请重新登录'));
        }

        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as ResponseData<T>);
        } else {
          reject(res.data);
        }
        if (config.showLoading) {
          // 请求成功后的操作
          setTimeout(() => {
            uni.hideToast(); // 延迟关闭提示框
          }, 50); // 延迟时间根据需要调整
        }
      },
      fail: (error) => {
        uni.showToast({ title: '网络连接失败', icon: 'none' });
        reject(error);
      },
      complete: () => {
        requestQueue.delete(requestKey);
      },
    });
  });

  requestQueue.set(requestKey, requestPromise);
  return requestPromise;
};

export default service;
